package com.jiawa.train.business.service;

import com.jiawa.train.business.entity.ConfirmOrderDoReq;
import com.jiawa.train.business.entity.ConfirmOrderTicketReq;
import com.jiawa.train.business.entity.RedisKeyPreEnum;
import com.jiawa.train.business.entity.StringRedisTemplate;
import com.jiawa.train.business.exception.BusinessException;
import com.jiawa.train.business.exception.BusinessExceptionEnum;
import com.jiawa.train.business.mapper.ConfirmOrderMapper;
import com.jiawa.train.business.service.DailyTrainTicketService;
import com.jiawa.train.business.service.DailyTrainCarriageService;
import com.jiawa.train.business.service.DailyTrainSeatService;
import com.jiawa.train.business.service.MemberTicketService;
import com.jiawa.train.util.DateUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.messaging.support.MessageBuilder;
import org.springframework.cloud.stream.messaging.Source;
import org.springframework.cloud.stream.annotation.Output;
import org.springframework.cloud.stream.annotation.EnableBinding;
import org.springframework.cloud.stream.annotation.StreamListener;
import org.springframework.cloud.stream.function.StreamBridge;
import com.alibaba.fastjson.JSON;

@Service
public class ConfirmOrderService {

    private static final Logger LOG = LoggerFactory.getLogger(ConfirmOrderService.class);

    @Resource
    private ConfirmOrderMapper confirmOrderMapper;

    @Resource
    private DailyTrainTicketService dailyTrainTicketService;

    @Resource
    private DailyTrainCarriageService dailyTrainCarriageService;

    @Resource
    private DailyTrainSeatService dailyTrainSeatService;

    @Resource
    private MemberTicketService memberTicketService;

    @Resource
    private StringRedisTemplate stringRedisTemplate;

    @Resource
    private StreamBridge streamBridge;

    public void save(ConfirmOrderDoReq req) {
        String tickets = req.getTickets();
        List<ConfirmOrderTicketReq> ticketsList = JSON.parseArray(tickets, ConfirmOrderTicketReq.class);
        for (ConfirmOrderTicketReq ticketReq : ticketsList) {
            String seat = ticketReq.getSeat();
            String[] split = seat.split("");
            String key = RedisKeyPreEnum.DAILY_TRAIN_SEAT_COUNT + ":" + DateUtil.formatDate(req.getDate()) + ":" + req.getTrainCode() + ":" + split[0];
            long decrement = stringRedisTemplate.opsForValue().decrement(key, -1);
            if (decrement < 0) {
                throw new BusinessException(BusinessExceptionEnum.CONFIRM_ORDER_TICKET_COUNT_ERROR);
            }
        }
    }

    public void doConfirm(ConfirmOrderDoReq req) {
        // 省略业务数据校验

        // 保存确认订单表，状态初始

        // ...

        // 选中座位后事务处理：
        // ...
        // 更新确认订单为成功

        // 发送异步消息，真正扣减数据库库存
        afterDoConfirm(req, finalTicketList);
    }

    private void afterDoConfirm(ConfirmOrderDoReq req, List<DailyTrainTicket> finalTicketList) {
        // ... 省略其他逻辑
        DailyTrainTicket finalTicket = finalTicketList.get(0);
        StockDeductDTO stockDeductDTO = new StockDeductDTO();
        stockDeductDTO.setDailyTrainTicketId(finalTicket.getId());
        stockDeductDTO.setTickets(req.getTickets());
        LOG.info("发送异步扣减库存消息：{}", JSON.toJSONString(stockDeductDTO));
        streamBridge.send("stockDeduct-out-0", stockDeductDTO);
    }
} 